<template>
  <div>
    <el-card
      :body-style="{ padding: '0px' }"
      :page-count="cur_pageSize"
      :total="total"
      :current-page="cur_page"
      @current-change="pageCurrentChangeHandle"
    >
      <el-form class="p-4" @submit.prevent.native inline>
        <el-form-item>
          <el-input
            v-model="remark"
            :placeholder="$t('batch.condition_remark')"
            maxlength="128"
            @keyup.enter.native="search"
            @blur="() => (this.remark = this.remark.trim())"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="w-8" @click="search">
            <svg-icon icon-class="Search" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            size="medium"
            class="w-8"
            type="primary"
            v-permission="{
              permission: '10400008.MANAGE',
              condition: {}
            }"
            @click="addTask()"
          >
            <svg-icon icon-class="Plus" />
          </el-button>
        </el-form-item>
      </el-form>
      <div
        v-permission="{
          permission: '10400008.MANAGE',
          condition: {}
        }"
        class="selected-batch-button flex"
        :class="selectedData.length > 0 ? 'active' : ''"
      >
        <span class="label" style="line-height: 25px">
          {{ selectedData.length }} {{ $t('common.deals') }}
        </span>
        <el-button
          class="w-8 ml-4"
          type="primary"
          :disabled="selectedData.length < 1"
          :class="selectedData.length >= 1 ? 'active' : ''"
          @click="handleDeleteTask"
        >
          <svg-icon icon-class="Delete" />
        </el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData"
        :show-overflow-tooltip="true"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" />
        <el-table-column :label="$t('batch.cmd_type')" prop="operationType">
          <template v-slot="{ row }">
            <div>
              <span>{{ cmdTypeFilter(row.operationType) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" :label="$t('batch.remark')" />
        <el-table-column prop="devNum" :label="$t('batch.device_num')" />
        <el-table-column :label="$t('common.create_time')">
          <template v-slot="{ row }"> {{ dateFilter(row.creTime) }}</template>
        </el-table-column>
        <el-table-column :label="$t('batch.process')">
          <template v-slot="{ row }">
            <div class="flex justify-center flex-col h-full">
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="fixNum(row)"
                status="success"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column width="75px">
          <template v-slot="scope">
            <el-button
              @click="handleRowClick({ command: 'details', row: scope.row })"
              text
              class="w-8"
            >
              <svg-icon icon-class="View"
            /></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import {
  delBatchOperations,
  queryBatchDevicePage,
  queryBatchOperationPage
} from '@/api/batch'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth'
import { dateFilter } from '@/filters'
import store from '@/store'

export default {
  components: {},
  props: {
    childData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      selectedData: [],
      batchId: this.childData.batchId,
      operationType: '',
      listLoading: false,
      remark: '',
      tableData: [],
      total: 0,
      cur_page: 1,
      cur_pageSize: 10,
      batchOperation: [],
      oneOperation: [{ action: 'delete', class: 'toolbar-delete' }],
      inputBox_importVisible: false,
      file_importVisible: false,
      tag_importVisible: false,
      importForm: {
        batchId: this.childData.batchId,
        devSn: undefined
      },
      operationTypes: [
        {
          val: 'command',
          name: 'Command'
        }
      ],
      importRule: {
        devSn: [
          {
            required: true,
            message: this.$t('batch.tip_addSn'),
            trigger: 'blur'
          },
          {
            min: 8,
            max: 20,
            message: this.$t('batch.tip_nameLength', { min: 8, max: 20 }),
            trigger: 'blur'
          }
        ]
      },
      headers: {
        'WEB-TOKEN': getToken(),
        LANG:
          localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
      }
    }
  },
  computed: {},
  created() {
    this.getTaskPageList()
  },
  methods: {
    dateFilter,
    operationTypeFilter(type) {
      const statusMap = {
        command: 'Command'
      }
      return statusMap[type]
    },
    onlineStatusFilter(status) {
      const statusMap = {
        0: 'Offline',
        1: 'Online'
      }
      return statusMap[status]
    },
    cmdTypeFilter(cmdTypeCode) {
      const cmdTypeMap = {
        A0: this.$t('command.desc.A0'),
        A1: this.$t('command.desc.A1'),
        A2: this.$t('command.desc.A2'),
        A3: this.$t('command.desc.A3'),
        A4: this.$t('command.desc.A4'),
        A5: this.$t('command.desc.A5'),
        A6: this.$t('command.desc.A6'),
        A7: this.$t('command.desc.A7'),
        A8: this.$t('command.desc.A8'),
        A9: this.$t('command.desc.A9'),
        AA: this.$t('command.desc.AA'),
        AB: this.$t('command.desc.AB'),
        AC: this.$t('command.desc.AC'),
        AD: this.$t('command.desc.AD'),
        B1: this.$t('command.desc.B1'),
        B2: this.$t('command.desc.B2'),
        B3: this.$t('command.desc.B3'),
        B4: this.$t('command.desc.B4'),
        B5: this.$t('command.desc.B5'),
        B6: this.$t('command.desc.B6'),
        B8: this.$t('command.desc.B8'),
        B9: this.$t('command.desc.B9'),
        BA: this.$t('command.desc.BA'),
        BB: this.$t('command.desc.BB'),
        D0: this.$t('command.desc.D0'),
        D1: this.$t('command.desc.D1'),
        D2: this.$t('command.desc.D2'),
        D5: this.$t('command.desc.D5'),
        D6: this.$t('command.desc.D6'),
        setting: this.$t('batch.operationTypes.setting')
      }
      return cmdTypeMap[cmdTypeCode]
    },
    handleSelectionChange(val) {
      this.selectedData = val
    },
    getTaskPageList() {
      this.listLoading = true
      queryBatchOperationPage({
        batchId: this.batchId,
        remark: this.remark,
        operationType: this.operationType,
        pageNo: this.cur_page,
        pageSize: this.cur_pageSize
      })
        .then((res) => {
          this.tableData = res.data
          this.total = res.rows
        })
        .finally(() => {
          this.listLoading = false
        })
      setTimeout(() => {
        this.listLoading = false
        this.$bus.emit('freshTerminalCount')
      }, 200)
    },
    handleDeleteTask() {
      this.$commonConfirm().showDeleteDialog(
        this.$t('common.common_confirm.delete_title'),
        this.$t('common.common_confirm.delete_content_operation'),
        this.$t('common.delete'),
        this.confirmDeleteTask
      )
    },
    confirmDeleteTask() {
      const batchOperationList = []
      this.selectedData.forEach((item) => {
        batchOperationList.push(item.batchOperationId)
      })
      delBatchOperations({
        batchId: this.batchId,
        batchOperationList: batchOperationList
      })
        .then((res) => {
          this.$message.success(this.$t('page.delete_success'))
          this.getTaskPageList()
        })
        .catch(this.$confirmError)
      this.$commonConfirm().close()
    },
    parseTime,
    pageCurrentChangeHandle(val) {
      this.cur_page = val
      this.getTaskPageList()
    },
    search() {
      this.cur_page = 1
      this.getTaskPageList()
    },
    async addTask() {
      await queryBatchDevicePage({
        batchId: this.batchId,
        recursive: 1,
        pageNo: this.cur_page,
        pageSize: this.cur_pageSize
      })
        .then((res) => {
          if (res.rows === 0) {
            this.$message.error(this.$t('batch.message.bind_terminal_tip'))
          } else {
            this.$router.push({
              path: `/tms/group/task/${this.batchId}`
            })
          }
        })
        .catch((e) => {
          this.$message({
            message: e.message,
            type: 'warning',
            duration: 5000
          })
        })
    },

    formatDate(row, column, cellValue, index) {
      return parseTime(cellValue, '{y}-{m}-{d}')
    },
    fixNum(row) {
      if (row.devNum > 0) {
        return parseFloat(
          parseFloat((row.succNum * 100) / row.devNum).toFixed(2)
        )
      } else return 0
    },
    progressFormat(percentage, row) {
      return `${percentage}%` + '   sum:' + row.devNum
    },
    handleRowClick(val) {
      const command = val.command
      const row = val.row
      if (command === 'details') {
        if (row.operationType === 'setting') {
          this.$router.push({
            name: 'taskDetail',
            params: row
          })
        } else {
          this.$router.push({
            name: 'taskDetailCmd',
            params: row
          })
        }
      } else if (command === 'edit') {
        // this.editTerminal(row)
      }
    }
  }
}
</script>

<style lang='scss'>
.group-terminal {
  .icon-button {
  }
}

.selected-batch-button {
  padding: 10px 20px;
  color: #c2c7ce;
  background-color: #edf2f9;

  &.active {
    color: #12263f;
    font-weight: 500;

    .button-box {
      border-left: 1px inset #12263f;

      button.active {
        background-color: #276dcb;

        color: white;
        cursor: pointer;

        &:hover {
          background-color: #2c7be5;
        }
      }
    }
  }

  .button-box {
    display: flex;
    margin-left: 15px;
    padding-left: 10px;

    border-left: 1px solid #c2c7ce;

    button {
      background-color: #d7dbe0;
      border-radius: 4px;
      height: 25px;
      margin: 1px 5px 1px 1px;
      padding: 0px 8px;
      cursor: not-allowed;

      .svg-icon {
        margin-right: 5px;
      }
    }
  }
}
</style>
